package com.evendai.sipdemo.util

import android.app.Activity
import android.content.Context
import android.content.Intent
import org.doubango.ngn.utils.NgnConfigurationEntry
import com.evendai.loglibrary.Timber
import com.evendai.sipdemo.Keys
import com.evendai.sipdemo.PersistentVariables
import com.evendai.sipdemo.bean.MeetingMessage
import com.evendai.sipdemo.camera.CameraActivity
import com.evendai.sipdemo.sip.audio.OutgoingService
import org.doubango.ngn.NgnEngine
import org.doubango.ngn.media.NgnMediaType
import org.doubango.ngn.sip.NgnAVSession
import org.doubango.ngn.sip.NgnMessagingSession
import org.jetbrains.anko.startActivity


object SipUtil {

    fun sendVideoMeetingSpeakPermission(enable: Boolean, meetingNumber: String) {
        val params = mutableMapOf(
            "type" to if (enable) "video_unmute" else "video_mute",
            "ipphone" to PersistentVariables.sipAccount,
            "group" to meetingNumber
        )
        val to = "pttservice$meetingNumber" // group为视频的会话号码，如查看球机30312，则group为90312.
        val sipMessage = JsonUtil.toJson(params)!!
        sendSipMessage(makeValidSipUri(to), sipMessage)
    }

    fun sendVideoMeetingListenPermission(enable: Boolean, meetingNumber: String) {
        val params = mutableMapOf(
            "type" to if (enable) "video_undeaf" else "video_deaf",
            "ipphone" to PersistentVariables.sipAccount,
            "group" to meetingNumber
        )
        val to = "pttservice$meetingNumber" // group为视频的会话号码，如查看球机30312，则group为90312.
        val sipMessage = JsonUtil.toJson(params)!!
        sendSipMessage(makeValidSipUri(to), sipMessage)
    }

    fun makeValidSipUri(remoteUri: String): String {
        val realm = NgnEngine.getInstance().configurationService.getString(NgnConfigurationEntry.NETWORK_REALM, NgnConfigurationEntry.DEFAULT_NETWORK_REALM)
        return "sip:${remoteUri}@$realm"
    }

    /** 邀请别人加入会议 */
    fun inviteMeeting(isAudio: Boolean) {
        val meetingNumber = if (isAudio) "${PersistentVariables.audioMeetingPrefix}${PersistentVariables.audioMeetingNumber}"
        else "${PersistentVariables.videoMeetingPrefix}${PersistentVariables.videoMeetingNumber}"

        val meetingMessage = MeetingMessage(
            action = MeetingMessage.ENTER_MEETING_ACTION,
            isAudio = isAudio,
            meetingNumber = meetingNumber,
            from = PersistentVariables.sipAccount,
            fromDisplayName = PersistentVariables.displayName
        )

        val json = JsonUtil.toJson(meetingMessage)!!
        sendSipMessage(makeValidSipUri(PersistentVariables.outgoingNumber), json)
    }

    /** 发送Sip消息到服务器 */
    fun sendSipMessageToServer(message: String) {
        val sipServerUri = makeValidSipUri("pttservices")
        sendSipMessage(sipServerUri, message)
    }

    fun sendSipMessage(receiverUri: String, message: String) {
        NgnEngine.getInstance().sipService?.let { sipService ->
            val messageSession = NgnMessagingSession.createOutgoingSession(sipService.sipStack, receiverUri)
            val sendResult = messageSession.sendTextMessage(message)
            NgnMessagingSession.releaseSession(messageSession)  // 发完消息后释放消息对象
            Timber.d("发送Sip消息给${receiverUri}结果：$sendResult, 消息内容：$message")
        }
    }

    /**
     * 发消息给服务器请求说话权限
     * @param groupSipCode 指定要请求哪个组的说话权限
     */
    fun requestSpeakPermission(groupSipCode: String) {
        // 发消息打开说话权限
        Timber.i("bgroup = $groupSipCode")
        // 进组后默认就有听的权限了，只需要发说的权限即可
        // val listenPermission = JsonUtil.toJson(mutableMapOf("type" to "talkback_undeaf", "ipphone" to LoginInfo.sipAccount, "group" to groupSipCode))!!
        val speakPermission = JsonUtil.toJson(mutableMapOf("type" to "talkback_unmute", "ipphone" to PersistentVariables.sipAccount, "group" to groupSipCode))!!
        val receiverUri = makeValidSipUri("msgservice")
        Timber.i("发送sip消息请求说话权限, 服务器uri = $receiverUri 消息内容: $speakPermission")
        // SipUtil.sendSipMessage(receiverUri, listenPermission)
        sendSipMessage(receiverUri, speakPermission)
    }

    fun callAudio(context: Context, isAudioMeeting: Boolean) {
        val outgoingNumber = when {
            isAudioMeeting -> "${PersistentVariables.audioMeetingPrefix}${PersistentVariables.audioMeetingNumber}"
            else -> PersistentVariables.outgoingNumber
        }

        context.startService(Intent(context, OutgoingService::class.java).apply {
            putExtra(Keys.OUTGOING_NUMBER, outgoingNumber)
        })
    }

    fun callVideo(context: Activity, isVideoMeeting: Boolean, isMainVideoMeeting: Boolean) {
        val outgoingNumber = when {
            isVideoMeeting -> "${PersistentVariables.videoMeetingPrefix}${PersistentVariables.videoMeetingNumber}"
            isMainVideoMeeting -> "${PersistentVariables.mainVideoMeetingPrefix}${PersistentVariables.videoMeetingNumber}"
            else -> PersistentVariables.outgoingNumber
        }

        context.startActivity<CameraActivity>(Keys.OUTGOING_NUMBER to outgoingNumber)
    }

    fun isVideoMeeting(outgoingNumber: String): Boolean {
        return PersistentVariables.videoMeetingPrefix.isNotBlank() && outgoingNumber.startsWith(PersistentVariables.videoMeetingPrefix)
    }

    fun isMainVideoMeeting(outgoingNumber: String): Boolean {
        return PersistentVariables.videoMeetingPrefix.isNotBlank() && outgoingNumber.startsWith(PersistentVariables.videoMeetingPrefix)
    }

    fun isAudioMeeting(outgoingNumber: String): Boolean {
        return PersistentVariables.audioMeetingPrefix.isNotBlank() && outgoingNumber.startsWith(PersistentVariables.audioMeetingPrefix)
    }

    fun requestVideoListenerAndSpeakPermission() {
        val remoteVideoGroup = PersistentVariables.videoMeetingNumber
        // video_undeaf
        val listenPermission = JsonUtil.toJson(mutableMapOf("type" to "talkback_undeaf", "ipphone" to PersistentVariables.sipAccount, "group" to remoteVideoGroup))!!
        val speakPermission = JsonUtil.toJson(mutableMapOf("type" to "talkback_unmute", "ipphone" to PersistentVariables.sipAccount, "group" to remoteVideoGroup))!!
        val receiverUri = makeValidSipUri("msgservice")
        sendSipMessage(receiverUri, listenPermission)
        sendSipMessage(receiverUri, speakPermission)
        Timber.i("已发送打开听说权限消息")
    }

    fun changeVideoMeetingType(isOnlyAudio: Boolean) {
        // 发消息打开视频画面
        val type = if (isOnlyAudio) "audio" else "video"
        val openVideoJson = "{\"action\":\"changeMeetingType\",\"type\":\"${type}\"}"
        Timber.i("已发送打开视频画面的消息，sipAccount = ${PersistentVariables.outgoingNumber}")
        val remoteUri = makeValidSipUri(PersistentVariables.outgoingNumber)
        sendSipMessage(remoteUri, openVideoJson)
    }

    /** 判断一个会话是否是视频电话 */
    fun isVideoCall(session: NgnAVSession): Boolean = session.mediaType == NgnMediaType.AudioVideo || session.mediaType == NgnMediaType.Video

}